'use strict';

const _ = require('underscore')
const Promise = require('bluebird')
const AV = require('leanengine')
const api = require('../wechat/wechatAPI')
const WECHAT_CONFIG = require('../wechat/config')
const rp = require('request-promise')

const findPlayers = function (player1, player2) {
  var query1 = new AV.Query('Doubles')
  var query2 = new AV.Query('Doubles')
  query1.equalTo('players', new AV.Object.createWithoutData('_User', player1))
  query2.equalTo('players', new AV.Object.createWithoutData('_User', player2))
  return AV.Query.and(query1, query2).find()
}

const func = {
  getDoublesByIds (req) {
    const doublesObjIds = req.params.doublesObjIds
    var s = {}
    var promises = doublesObjIds.map(el => {
      return new AV.Query('Doubles').get(el)
      .then(ret => {
        var relation = ret.relation('players')
        var query = relation.query()
        return query.find()
        .then(ret2 => {
          return Promise.resolve({
            objectId: ret.id,
            name: ret.get('name'),
            players: ret2.map(el => el.id)
          })
        })
      })
    })
    return Promise.all(promises)
  },

  getMyDoubles (req) {
    var s = {}
    var query = new AV.Query('Doubles')
    query.equalTo('players', req.user)
    return query.find().then(ret => {
      s.doubles = ret.map(el => {
        return el.toJSON()
      })
      var promises = ret.map(el => {
        var relation = el.relation('players')
        var q = relation.query()
        return q.find()
      })
      return Promise.all(promises)
    }).then(ret => {
      ret.forEach((el, index) => {
        s.doubles[index].players = el
      })
      return Promise.resolve(s.doubles)
    })
  },

  invite (req) {
    const phone = req.params.phone
    const nickname = req.params.nickname
    var userObjId
    if (phone === req.user.get('mobilePhoneNumber')) {
      return Promise.reject({errMsg: 'cannot invite yourself', errMsgCN: '不能邀请你自己'})
    }
    if (phone) {
      return new AV.Query('_User').equalTo('mobilePhoneNumber', phone).find().then(ret => {
        if (!ret.length) {
          return Promise.reject({errMsg: 'cannot find the user', errMsgCN: '不存在该用户'})
        }
        userObjId = ret[0].id
        return findPlayers(userObjId, req.user.id).then(ret => {
          if (ret.length) {
            return Promise.reject({errMsg: 'has teamed', errMsgCN: '你已经与对方组成双打队伍'})
          }
          return new AV.Query('_User').get(userObjId)
        }).then(ret => {
          let content = `${req.user.get('nickname')}邀请你与TA组成双打队伍\n<a href="${WECHAT_CONFIG.host}/#!/notification">接受</a>`
          api.sendText(ret.get('openid'), content, function () {
            console.log(arguments)
          })
          return rp({
            uri: `https://birdie2.wilddogio.com/notification/${userObjId}.json`,
            method: 'POST',
            body: JSON.stringify({
              type: 'doublesInvitation',
              inviterObjId: req.user.id,
              createdAt: new Date().toISOString()
            })
          })
        })
      })
    }
  },

  accept (req) {
    const doublesObjId = req.params.doublesObjId
    const inviterObjId = req.params.inviterObjId
    return findPlayers(inviterObjId, req.user.id).then(ret => {
      if (ret.length) {
        return Promise.reject({errMsg: 'has teamed'})
      }
      var doubles = new AV.Object('Doubles')
      var relation = doubles.relation('players')
      relation.add(req.user)
      relation.add(new AV.Object.createWithoutData('_User', inviterObjId))
      return doubles.save()
    }).then(ret => {
      return new AV.Query('_User').get(inviterObjId)
    }).then(ret => {
      let content = `${req.user.get('nickname')}已经与你组成双打队伍\n<a href="${WECHAT_CONFIG.host}/#!/user/doubles">查看我的双打队伍</a>`
      api.sendText(ret.get('openid'), content, () => {

      })
      return Promise.resolve()
    })
  }
}

AV.Cloud.define('doubles', function (req, res) {
  var promise
  if (!req.user) {
    promise = Promise.reject({
      msg: 'not loged in'
    })
  } else {
    promise = func[req.params.method](req)
  }
  return promise.then(function (ret) {
    res.success(ret)
  }).catch(function (err) {
    console.log(err)
    res.error(err)
  })
})
